import router from './router'
import store from './store'
import { Message, MessageBox } from 'element-ui'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { getToken } from '@/utils/auth'
import { inSubstrate } from '@/utils/parent_connect/receiveParentApi'

NProgress.configure({ showSpinner: false })

const whiteList = ['/login', '/auth-redirect', '/bind','/chooseDept','/pwdChange','/pwdSet',
  /*'/ibps/ebankLogin',
  '/ibps/toTrans',
  '/ibps/accountTrans',
  '/ibps/phoneTrans'*/]

router.beforeEach((to, from, next) => {
  if(!inSubstrate())
    NProgress.start()
  if (getToken()) {

    /* has token*/
    if (to.path === '/login') {

      next()
    } else {
      if (whiteList.indexOf(to.path) > -1) {
        // 在白名单中直接跳转 还不需要加载路由 否则加载路由接口是会出错的(有多机构的时候 不选择机构加载菜单是会错误的)
        next()
      } else {

        if(!store.getters.permission_routes || store.getters.permission_routes.length == 0) {

          store.dispatch("GetInfo").then((res) => {})
          store.dispatch('GenerateRoutes').then(accessRoutes => {
            // 根据roles权限生成可访问的路由表
            router.addRoutes(accessRoutes) // 动态添加可访问路由表
            next({ ...to, replace: true }).catch(()=>{}) // hack方法 确保addRoutes已完成
          }).catch(res=> {
            console.log('cache route')
            next()
          })

        } else {
          next()
        }
      }
    }
  } else {
    // 没有token
    if (whiteList.indexOf(to.path) !== -1) {
      // 在免登录白名单，直接进入
      next()
    } else {
      next(`/login`) // 否则全部重定向到登录页 ?redirect=${to.fullPath}
    }
  }
})

router.afterEach(() => {
  if(!inSubstrate())
    NProgress.done()
})
